package com.managermype.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Component;

import com.managermype.business.MessageBusiness;
import com.managermype.business.UserBusiness;
import com.managermype.domain.Role;
import com.managermype.domain.User;
import com.managermype.exception.ManagerMypeAuthException;
import com.managermype.exception.ManagerMypeException;
import com.managermype.util.Error;

/**
 * 
 * @author juandiego
 * 
 */

@SuppressWarnings("deprecation")
@Component("authenticationProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider {

	@Autowired
	private User user;
	@Autowired
	private UserBusiness userBusiness;
	@Autowired
	private MessageBusiness messageBusines;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		System.out.println(authentication.toString());
		System.out.println("Usuario: " + authentication.getName());
		System.out.println("Constraseña: " + authentication.getCredentials().toString());
		System.out.println("Detalle:" + authentication.getDetails().toString());

		try {
			user = userBusiness.loginUser(authentication.getName(), authentication.getCredentials().toString());
			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			for (Role role : user.getMyRoles()) {
				authorities.add(new GrantedAuthorityImpl(role.getDescription()));
			}
			return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), authorities);
		}
		catch (ManagerMypeException e) {
			System.err.println(e.getMessage());
			throw new ManagerMypeAuthException(e.getMessage());
		}
		catch (AuthenticationException e) {
			throw e;
		}
		catch (Exception e) {
			System.err.println(messageBusines.getInternalDescriptionMessage(Error.GENERIC_ERROR.getErrorCode()));
			throw new ManagerMypeAuthException(e.toString());
		}

	}

	@Override
	public boolean supports(Class<?> authentication) {
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}

}
